<template>
  <div>
    <el-dialog :visible="editVis" @close="handleClose" :title="diaTitle" width="40%">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="110px">
        <div v-for="item in formColumns" :key="item.prop">
          <el-form-item :label="item.label" :prop="item.prop">
            <!-- 💭输入框 -->
            <el-input
              v-if="item.ele === 'input'"
              v-model="formData[item.prop]"
              size="mini"
              style="width: 50%"
              clearable
            ></el-input>
            <!-- 💭单选按钮 -->
            <el-radio-group size="mini" v-if="item.ele === 'radio'" v-model="formData[item.prop]">
              <el-radio v-for="it in item.radios" :key="it.label" :label="it.label" v-model="it.value"></el-radio>
            </el-radio-group>
            <!-- 💭下拉框 -->
            <el-select size="mini" v-if="item.ele === 'select'" v-model="formData[item.prop]" style="width: 50%">
              <el-option v-for="it in item.options" :key="it.value" :label="it.label" :value="it.value"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 💭树形表单项 -->
        <el-form-item label="菜单权限：">
          <section class="form_tree_part">
            <!-- 菜单部分 -->
            <div class="button_part">
              <el-checkbox v-model="checkedOne" @change="changeOne">展开/折叠</el-checkbox>
              <el-checkbox v-model="checkedTwo" @change="changeTwo">全选/全不选</el-checkbox>
            </div>
            <!-- 树形 -->
            <div class="tree_part" style="width: 90%; height: 200px; overflow: auto">
              <el-tree
                ref="treeRef"
                :props="defaultProps"
                :data="treeData"
                :default-expanded-keys="defaultExpandedCids"
                show-checkbox
                node-key="id"
                check-on-click-node
                default-expand-all
              >
              </el-tree>
            </div>
          </section>
        </el-form-item>
        <!-- 💭文本域 -->
        <el-form-item label="描述：" prop="remark">
          <el-input type="textarea" v-model="formData.remark" size="mini" style="width: 90%" clearable></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="btnConfirm">确认</el-button>
        <el-button size="mini" @click="btnCancel">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  props: {
    editVis: {
      type: Boolean,
      default: false,
    },
    diaType: {
      type: String,
    },
    editData: {
      type: Object,
    },
    selectedMenus: {
      type: Array,
    },
  },
  data() {
    return {
      diaTitle: '',
      // 表单渲染规则
      formColumns: [
        { ele: 'input', prop: 'name', label: '角色名称：' },
        { ele: 'input', prop: 'code', label: '角色代码：' },
      ],
      // 表单数据
      formData: {},
      formRules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        code: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
      menuPermission: [],
      defaultProps: {
        label: 'name',
        children: 'children',
      },
      // 树形渲染数据
      treeData: [],
      checkedOne: false,
      checkedTwo: false,
      // 树所有可选择的子节点
      treeAllChildNode: [],
      defaultExpandedCids: [],
    }
  },
  watch: {
    diaType(newV, oldV) {
      if (newV === 'add') {
        this.diaTitle = '新建角色'
      } else if (newV === 'edit') {
        this.diaTitle = '修改角色'
      } else if (newV === 'copy') {
        this.diaTitle = '复制角色'
      }
    },
    editData(newV, oldV) {
      if (Object.values(newV).length !== 0) {
        this.formData = { ...newV }
        this.$nextTick(() => {
          this.$refs.treeRef.setCheckedKeys(newV.menuIds)
        })
      } else {
        this.formData = {
          name: '',
          code: '',
          type: 1,
          remark: '',
        }
      }
    },
    editVis(val) {
      if (val) {
        if (this.editData.menuIds && this.editData.menuIds.length > 0) {
          if (this.selectedMenus.length > 0) {
            const checkTreeNode = []
            this.defaultExpandedCids = this.selectedMenus
            this.$nextTick(() => {
              this.selectedMenus.forEach(value => {
                const node = this.$refs.treeRef.getNode(value)
                if (node) {
                  if (node.isLeaf) {
                    checkTreeNode.push(value.id)
                  }
                }
                // 设置默认选中
                this.$nextTick(() => {
                  this.$refs.treeRef.setCheckedKeys(checkTreeNode)
                })
              })
            })
          }
        }
      }
    },
  },
  created() {
    this.getTreeData()
  },
  methods: {
    ...mapActions('menuConfig', ['getMenuDataAPI']),

    publicClose() {
      this.$refs.formRef.resetFields()
      this.checkedOne = false
      this.checkedTwo = false
      this.$refs.treeRef.setCheckedKeys([])
      this.$emit('update:editVis', false)
    },
    handleClose() {
      this.publicClose()
    },
    async btnConfirm() {
      const checkedNodes = this.$refs.treeRef.getCheckedNodes(false, true)
      const menuIds = []
      checkedNodes &&
        checkedNodes.forEach(item => {
          menuIds.push(item.id)
        })
      this.formData.menuIds = menuIds
      await this.$refs.formRef.validate()
      if (this.diaType === 'add') {
        this.$emit('createRoleData', this.formData)
      } else if (this.diaType === 'edit') {
        this.$emit('updateRoleData', this.formData)
      } else if (this.diaType === 'copy') {
        this.$emit('createRoleData', this.formData)
      }
      this.publicClose()
    },
    btnCancel() {
      this.publicClose()
    },
    // 🏀获取树形数据
    getTreeData() {
      const params = {
        name: '',
      }
      this.getMenuDataAPI({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          data.map((dItem, dIndex) => {
            if (dItem.name !== '系统管理' && dItem.name !== '项目中心' && dItem.name !== 'EDCBuilder') {
              this.treeData.push(dItem)
            }
          })
          this.treeAllChildNode = []
          this.getTreeAllChildNode(this.treeData)
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },
    // 🏀递归获取树所有可选择的子节点
    getTreeAllChildNode(treeData) {
      // 树长度为0 结束操作
      if (treeData.length === 0) {
        return
      }
      // 遍历树的数据
      for (let i = 0; i < treeData.length; i++) {
        // 当前遍历的数据是否还有子节点
        const children = treeData[i].children
        if (children && children.length > 0) {
          // 有，则递归
          this.getTreeAllChildNode(children)
        } else {
          this.treeAllChildNode.push(treeData[i].id)
        }
      }
    },
    // 展开折叠切换
    changeOne(val) {
      for (var i = 0; i < this.$refs.treeRef.store._getAllNodes().length; i++) {
        // 根据isExpand， tree展开或折叠
        this.$refs.treeRef.store._getAllNodes()[i].expanded = val
      }
    },
    // 🏀全选切换
    changeTwo(val) {
      if (val) {
        // 遍历将子节点全选中
        for (let i = 0; i < this.treeAllChildNode.length; i++) {
          this.$refs.treeRef.setChecked(this.treeAllChildNode[i], true)
        }
      } else {
        // 全部不选中
        this.$refs.treeRef.setCheckedNodes([])
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.form_tree_part {
  .button_part {
    display: flex;
  }
  .tree_part {
    border: 1px solid #e5e6e7;
  }
}
</style>
